package com.twu.biblioteca;

public class BibliotecaApp {

    private IO io;
    private Menu menu;
    private Books books;
    private Movie movie;
    private Login login;

    public BibliotecaApp(IO io, Menu menu, Books books) {

        this.io = io;
        this.menu = menu;
        this.books = books;
    }

    public void run() {
        login = new Login(io);
        login.loginValidator();
        io.display("Welcome to Biblioteca!\n" + menu);
        selectedOption();
    }

    public void displayBooks() {
        StringBuilder stringBuilder = new StringBuilder();

        for (Book displayBook : books.getBooks()) {
            stringBuilder.append(displayBook.getBookTitle());
            stringBuilder.append("\n");
        }
        io.display(stringBuilder.toString());

    }

    private void selectedOption() {
        boolean validOption;
        do {
            try {
                int optionSelected;
                io.display("Select your option in the menu or type letter z to quit");
                optionSelected = io.nextInt();
                validOption = menu.validate(optionSelected);

                if (!validOption) {
                    io.display("Select a valid option!");
                } else {
                    DisplayOptionSelectedResult(optionSelected);
                }
            } catch (Exception e) {
            }
        } while (!(io.nextLine().contains("z")));

        io.display("Thank you for using Biblioteca application!!");

    }

    private void DisplayOptionSelectedResult(int optionSelected) {

        if (optionSelected == OptionSelect.VIEW_ALL_BOOKS.getMenuIndex()) {
            displayBooks();
        } else
        if (optionSelected == OptionSelect.RESERVE_BOOK.getMenuIndex()) {
            displayBooks();
           io.display("Please select a book to reserve\n ");
            handleReservation(io.nextInt());
        }else
        if (optionSelected == OptionSelect.CUSTOMER_DETAILS.getMenuIndex()){
            io.display("Please talk to a Librarian. Thank you.");
        } else
            if (optionSelected == OptionSelect.MOVIES.getMenuIndex()){
                movie = new Movie();
                io.display(movie.toString());
            }
    }

    private void handleReservation(int i) {
        Book book = books.getBooks().get(i);
        if (!book.isReserved()) {
            book.setReserved(true);
            io.display("Thank you, enjoy the book!");
        } else {
            io.display("Sorry we don't have that book yet.");
        }
    }

}
